package com.dongnao.network.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 伪异步
 */
public class FakeAsyncServer {

    //自定义线程池
    public static ExecutorService service = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
            60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>());


    public static void main(String[] args) throws IOException {
        //服务器端口注册
        ServerSocket ss = new ServerSocket(9999);

        while (true) {
            //监听客户端的socket连接请求
            Socket socket = ss.accept();

            SockedThread sockedThread = new SockedThread(socket);
            service.submit(sockedThread);
        }
    }

    static class SockedThread implements Runnable {
        Socket socket;

        public SockedThread(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            //从Socket管道中得到一个字节输入流
            try {
                InputStream inputStream = socket.getInputStream();
                //把字节输入流包装成字符缓冲输入流                           //把字节转为字符
                BufferedReader bufferedInputStream = new BufferedReader(new InputStreamReader(inputStream));
                String msg;
                while ((msg = bufferedInputStream.readLine()) != null) {
                    long id = Thread.currentThread().getId();
                    System.out.println("服务端的线程" + id + "接收：" + msg);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
